﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Imdb;
using System.Collections;
using System.IO;
using System.Xml.Serialization;
using System.Threading;
using MoviesManager.Helpers;
using MoviesManager.Library;
using MoviesManager.Enums;

namespace MoviesManager
{
    public partial class Form1 : Form
    {
        string moviesFolderPath = @"D:\MoviesMangager";
        //List<MovieFolder> movieFolderBindingSource = new List<MovieFolder>();
        Imdb.Services Imdb = new Services();
        FiltersCollection MFiltersCollection = new FiltersCollection();
        VMovieCollection VMCollection = new VMovieCollection();

        VMovie CurrentMovie = new VMovie();
        Movie SelectedMovie = new Movie();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Imdb.FoundMovies += new FoundMoviesEventHandler(Imdb_FoundMovies);
            Imdb.MovieParsed += new MovieParsedEventHandler(Imdb_MovieParsed);
            
            FillMoviesFolders();
            LoadFilters();
        }

        private void ReBindMovies()
        {
            BSmovieFolder.DataSource = null;
            BSmovieFolder.DataSource = VMCollection;
            if (lbMoves.SelectedIndex != -1)
                lbMoves.SetSelected(0, false);
            dgvMoviesNamesInfo.ClearSelection();
        }

        private void ReBindFilters()
        {
            BSmovieFilters.DataSource = null;
            BSmovieFilters.DataSource = MFiltersCollection;    
            BSmovieFilterTypes.DataSource = Enum.GetValues(typeof(FilterType));
        }

        private void btnBrowseMovie_Click(object sender, EventArgs e)
        {
            if (dialogMovieBrowser.ShowDialog() == DialogResult.OK)
                moviesFolderPath = dialogMovieBrowser.SelectedPath;

            txtMoviePath.Text = moviesFolderPath;
            FillMoviesFolders();

            
        }

        private void FillMoviesFolders()
        {
            DirectoryInfo folder = new DirectoryInfo(moviesFolderPath);
            string[] files;

            if (folder.Exists)
            {
                string[] Folder;
                Folder = Directory.GetDirectories(moviesFolderPath);
                foreach (string FolderName in Folder)
                {
                    FileInfo fi = new FileInfo(FolderName);
                    
                    VMovie mFolder = new VMovie();

                    mFolder.FullPath = fi.FullName;
                    mFolder.OriginalName = fi.Name;
                    mFolder.ID = fi.Name.GetHashCode();
                    mFolder.NewName = fi.Name;

                    files = Directory.GetFiles(fi.FullName);
                    foreach (var item in files)
                    {

                        FileInfo fileNameInfo = new FileInfo(item);
                        mFolder.MovieFiles.Add(fileNameInfo);
                    }

                    mFolder.ImdbSynchronisationDone += new ImdbSynchronisation(IMDBSynchDone);
                    VMCollection.Add(mFolder);
                    
                }
            }
            LoadMovieCollectionFromConfig();
            ReBindMovies();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Imdb.FindMovie(txtSearch.Text.Replace('.', ' '));
        }

        void Imdb_MovieParsed(Movie M)
        {
            FillIfExcist(M);
            SelectedMovie = M;
            BindImdbMovieDetailInfoControls(SelectedMovie);
            download_Poster(SelectedMovie);
            Cursor.Current = Cursors.Arrow;
        }

        void Imdb_FoundMovies(MoviesResultset M)
        {
           var temp = ((VMovie)VMCollection.FirstOrDefault(p => p.NewName.ToLower() == M.SearchedMovieName.ToLower()));
           temp.MoviesIMDBResultset = M;
           temp.TryToChooceMovie();
        }

        private void FillIfExcist(Movie M)
        {
            Movie temoM;
            int i;
            if (CurrentMovie.MoviesIMDBResultset.PopularTitles != null && CurrentMovie.MoviesIMDBResultset.PopularTitles.Exists(p => p.Id == M.Id))
            {
                temoM = CurrentMovie.MoviesIMDBResultset.PopularTitles.Find(p => p.Id == M.Id);
                if (!temoM.AlreadyDownloaded)
                {
                    M.AlreadyDownloaded = true;
                    i = CurrentMovie.MoviesIMDBResultset.PopularTitles.IndexOf(temoM);
                    CurrentMovie.MoviesIMDBResultset.PopularTitles.Remove(temoM);
                    CurrentMovie.MoviesIMDBResultset.PopularTitles.Insert(i, M);
                }
                return;
            }
            if (CurrentMovie.MoviesIMDBResultset.ExactMatches != null && CurrentMovie.MoviesIMDBResultset.ExactMatches.Exists(p => p.Id == M.Id))
            {
                temoM = CurrentMovie.MoviesIMDBResultset.ExactMatches.Find(p => p.Id == M.Id);
                if (!temoM.AlreadyDownloaded)
                {
                    M.AlreadyDownloaded = true;
                    i = CurrentMovie.MoviesIMDBResultset.ExactMatches.IndexOf(temoM);
                    CurrentMovie.MoviesIMDBResultset.ExactMatches.Remove(temoM);
                    CurrentMovie.MoviesIMDBResultset.ExactMatches.Insert(i, M);
                }
                return;
            }
            if (CurrentMovie.MoviesIMDBResultset.PartialMatches != null && CurrentMovie.MoviesIMDBResultset.PartialMatches.Exists(p => p.Id == M.Id))
            {
                temoM = CurrentMovie.MoviesIMDBResultset.PartialMatches.Find(p => p.Id == M.Id);
                if (!temoM.AlreadyDownloaded)
                {
                    M.AlreadyDownloaded = true;
                    i = CurrentMovie.MoviesIMDBResultset.PartialMatches.IndexOf(temoM);
                    CurrentMovie.MoviesIMDBResultset.PartialMatches.Remove(temoM);
                    CurrentMovie.MoviesIMDBResultset.PartialMatches.Insert(i, M);
                }
                return;
            }
        }

        private void btnSaveFilters_Click(object sender, EventArgs e)
        {
            XmlSerializer xser = new XmlSerializer(typeof(FiltersCollection));
            var theStream = File.Open(@"MovieFiltersContent.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            xser.Serialize(theStream, MFiltersCollection);
            theStream.Close();
            MessageBox.Show("It's Saved");

        }

        private void LoadFilters()
        {
            XmlSerializer xser = new XmlSerializer(typeof(FiltersCollection));
            if (File.Exists(@"MovieFiltersContent.xml"))
            {
                var theStream = File.Open(@"MovieFiltersContent.xml", FileMode.Open, FileAccess.Read);
                MFiltersCollection = (FiltersCollection)xser.Deserialize(theStream);
                theStream.Close();
            }
            ReBindFilters();
        }

       private void ApplyFiltersToFolders()
       {
           string temp;
           foreach (VMovie item in VMCollection)
           {
               item.NewName = item.NewName.Replace('.', ' ').ToLower();
               int tempYear = 0;

               foreach (var filter in MFiltersCollection)
               {
                   if (filter.Type == FilterType.Year && item.NewName.Contains(filter.FilterValue))
                       if(int.TryParse(filter.FilterValue, out tempYear))
                           item.YearByName = tempYear;

                   item.NewName = item.NewName.ToLower().Replace(filter.FilterValue.ToLower(), "");
                  
               }
               temp = item.NewName.Split(' ').FirstOrDefault(p => p.StartsWith("-"));
               if (!string.IsNullOrEmpty(temp))
                    item.NewName = item.NewName.Replace(temp, "");

               item.NewName = item.NewName.TrimEnd();
               item.NewName = FileNamesHelpers.ToTitleCase(item.NewName);
           }
       }

      
       private void btnApplyFilters_Click(object sender, EventArgs e)
       {
           ApplyFiltersToFolders();
           dgvMoviesNamesInfo.Refresh();
       }

       private void tabPage1_Click(object sender, EventArgs e)
       {

       }

       private void btnApplyToFolders_Click(object sender, EventArgs e)
       {
           List<string> errorsFolders = new List<string>();
           foreach (VMovie item in BSmovieFolder.List)
           {
               if (item.MovieStatus == moviesStatuses.ImdbSynched)
               {
                   try
                   {
                       item.NewName = ApplyNamePattern(item);
                       item.MovieStatus = moviesStatuses.ImdbSynched;
                       item.ID = item.NewName.GetHashCode();
                       if (Directory.Exists(moviesFolderPath) && !string.IsNullOrEmpty(item.NewName))
                       {

                           Directory.Move(Path.Combine(moviesFolderPath, item.OriginalName), Path.Combine(moviesFolderPath, item.NewName));
                       }
                       item.OriginalName = item.NewName;
                       item.MovieIMDBInfo.Poster.Save(Path.Combine(Path.Combine(moviesFolderPath, item.NewName), "Folder.jpg"));
                   }

                   catch (Exception exx)
                   {
                       errorsFolders.Add(item.OriginalName + " ( " + exx.Message + " )");
                   }
               }
           }

           if (errorsFolders.Count == 0)
               MessageBox.Show("Directory Names are Fixed");
           else
           {
               string errorMessage = "The Folowing Folders were not Renamed: \r\n ";
               foreach (var item in errorsFolders)
               {
                   errorMessage += "\r\n" + item;
               }
               //errorMessage += "\r\n \r\n ";
               MessageBox.Show(errorMessage);
           }

           SaveMovieCollectionToConfig();
           VMCollection.Clear();
           FillMoviesFolders();
       }

       private string ApplyNamePattern(VMovie vm)
       {
           return String.Format("{0} ({1})",vm.NewName,vm.MovieIMDBInfo.UserRating);
       }

       private void button1_Click_1(object sender, EventArgs e)
       {
           FolderHelpers.CopyFolder(@"Z:\Movies", moviesFolderPath);
           MessageBox.Show("The Folder Titles successfully copied");
           
           FillMoviesFolders();
       }


       private void download_Poster(Movie M)
       {
           M.Poster = Properties.Resources.ajax_loader;
           using (var Wc = new System.Net.WebClient())
           {
               Wc.DownloadDataCompleted += new System.Net.DownloadDataCompletedEventHandler(Wc_DownloadDataCompleted);
               Wc.DownloadDataAsync(new Uri(M.PosterUrl));
           }
       }

       private void Wc_DownloadDataCompleted(object sender, System.Net.DownloadDataCompletedEventArgs e)
       {
           ((System.Net.WebClient)sender).DownloadDataCompleted -= Wc_DownloadDataCompleted;
           {
               pictureBox1.Image = System.Drawing.Image.FromStream(new System.IO.MemoryStream(e.Result));
               if (CurrentMovie.MovieIMDBInfo != null && SelectedMovie.Id == CurrentMovie.MovieIMDBInfo.Id)
                   CurrentMovie.MovieIMDBInfo.Poster = pictureBox1.Image;
               SelectedMovie.Poster = pictureBox1.Image;
           }
       }

       private void lbExactMatches_SelectedValueChanged(object sender, EventArgs e)
       {
           Cursor.Current = Cursors.WaitCursor;
           if (lbExactMatches.SelectedIndex != -1)
           {
               var temp = (CurrentMovie.MoviesIMDBResultset.ExactMatches.Find(p=>p.Id == ((Movie)lbExactMatches.SelectedItem).Id));
               lbPopularTitles.SelectedIndex = -1;
               lbPartialMatches.SelectedIndex = -1;
               if (CurrentMovie.MovieIMDBInfo != null && ((Movie)lbExactMatches.SelectedItem).Id == CurrentMovie.MovieIMDBInfo.Id)
               {
                   btnApply.Enabled = false;
                   SelectedMovie = CurrentMovie.MovieIMDBInfo;
                   BindImdbMovieDetailInfoControls(SelectedMovie);
                   if (SelectedMovie.Poster == null)
                       download_Poster(SelectedMovie);
                   Cursor.Current = Cursors.Arrow;
               }
               else if (temp.AlreadyDownloaded)
               {
                   btnApply.Enabled = true;
                   SelectedMovie = temp;
                   BindImdbMovieDetailInfoControls(CurrentMovie.MoviesIMDBResultset.ExactMatches.Find(p => p.Id == ((Movie)lbExactMatches.SelectedItem).Id));
                   if (temp.Poster == null)
                       download_Poster(temp);
                   Cursor.Current = Cursors.Arrow;
               }
               else
               {
                   btnApply.Enabled = true;
                   Imdb.GetMovieAsync(((Movie)lbExactMatches.SelectedItem).Id, false); //0499549 avatar  //0133093 matrix
               }
           }
       }

       private void lbPartialMatches_SelectedValueChanged(object sender, EventArgs e)
       {
           Cursor.Current = Cursors.WaitCursor;
           if (lbPartialMatches.SelectedIndex != -1)
           {
               var temp = (CurrentMovie.MoviesIMDBResultset.PartialMatches.Find(p => p.Id == ((Movie)lbPartialMatches.SelectedItem).Id));
               lbExactMatches.SelectedIndex = -1;
               lbPopularTitles.SelectedIndex = -1;
               if (CurrentMovie.MovieIMDBInfo != null && ((Movie)lbPartialMatches.SelectedItem).Id == CurrentMovie.MovieIMDBInfo.Id)
               {
                   btnApply.Enabled = false;
                   SelectedMovie = CurrentMovie.MovieIMDBInfo;
                   BindImdbMovieDetailInfoControls(SelectedMovie);
                   if (SelectedMovie.Poster == null)
                       download_Poster(SelectedMovie);
                   Cursor.Current = Cursors.Arrow;
               }
               else if (temp.AlreadyDownloaded)
               {
                   btnApply.Enabled = true;
                   SelectedMovie = temp;
                   BindImdbMovieDetailInfoControls(CurrentMovie.MoviesIMDBResultset.PartialMatches.Find(p => p.Id == ((Movie)lbPartialMatches.SelectedItem).Id));
                   if (temp.Poster == null)
                       download_Poster(temp);
                   Cursor.Current = Cursors.Arrow;
               }
               else
               {
                   btnApply.Enabled = true;
                   Imdb.GetMovieAsync(((Movie)lbPartialMatches.SelectedItem).Id, false); //0499549 avatar  //0133093 matrix
               }
           }
           
       }

       private void lbPopularTitles_SelectedValueChanged(object sender, EventArgs e)
       {
           Cursor.Current = Cursors.WaitCursor;
           if (lbPopularTitles.SelectedIndex != -1)
           {
               var temp = (CurrentMovie.MoviesIMDBResultset.PopularTitles.Find(p => p.Id == ((Movie)lbPopularTitles.SelectedItem).Id));
               lbExactMatches.SelectedIndex = -1;
               lbPartialMatches.SelectedIndex = -1;
               if (CurrentMovie.MovieIMDBInfo != null && ((Movie)lbPopularTitles.SelectedItem).Id == CurrentMovie.MovieIMDBInfo.Id)
               {
                   btnApply.Enabled = false;
                   SelectedMovie = CurrentMovie.MovieIMDBInfo;
                   BindImdbMovieDetailInfoControls(SelectedMovie);
                   if (SelectedMovie.Poster == null)
                       download_Poster(SelectedMovie);
                   Cursor.Current = Cursors.Arrow;
               }
               else if (temp.AlreadyDownloaded)
               {
                   btnApply.Enabled = true;
                   SelectedMovie = temp;
                   BindImdbMovieDetailInfoControls(CurrentMovie.MoviesIMDBResultset.PopularTitles.Find(p => p.Id == ((Movie)lbPopularTitles.SelectedItem).Id));
                   if (temp.Poster == null)
                       download_Poster(temp);
                   Cursor.Current = Cursors.Arrow;
               }
               else
               {
                   btnApply.Enabled = true;
                   Imdb.GetMovieAsync(((Movie)lbPopularTitles.SelectedItem).Id, false); //0499549 avatar  //0133093 matrix
               }
           }
          
       }

       private void lbMoves_SelectedIndexChanged(object sender, EventArgs e)
       {
           if (tabMain.SelectedTab.Name == "tbIMDB")
           {
               if (((ListBox)sender).SelectedIndex != -1)
               {
                   CleanImdbInfoControls();
                   switch (((VMovie)((ListBox)sender).SelectedItem).MovieStatus)
                   {
                       case moviesStatuses.None:
                           btnIMDBSingleSynch.Enabled = true;
                           break;
                       case moviesStatuses.ImdbSynched:
                       case moviesStatuses.ImdbNotSynched:
                           btnIMDBSingleSynch.Enabled = false;
                           CurrentMovie = ((VMovie)((ListBox)sender).SelectedItem);
                           if (CurrentMovie.MoviesIMDBResultset != null)
                               BindImdbInfoControls();
                           break;
                   }
               }
           }
       }

       private void BindImdbInfoControls()
       {
           if (CurrentMovie.MoviesIMDBResultset.PopularTitles != null)
           {
               lbPopularTitles.Items.AddRange(CurrentMovie.MoviesIMDBResultset.PopularTitles.ToArray());
               lbPopularTitles.DisplayMember = "Title";
               lbPopularTitles.ValueMember = "Id";
               if (CurrentMovie.MovieChoosedFrom == choosedFrom.PopularTitles)
               {
                   int tempIndex = -1;
                   foreach (Movie item in lbPopularTitles.Items)
                   {
                       if (item.Id == CurrentMovie.MovieIMDBInfo.Id)
                       {
                           tempIndex = lbPopularTitles.Items.IndexOf(item);
                       }
                   }
                   if (tempIndex != -1)
                       lbPopularTitles.SetSelected(tempIndex, true);
               }
           }

           if (CurrentMovie.MoviesIMDBResultset.ExactMatches != null)
           {
               lbExactMatches.Items.AddRange(CurrentMovie.MoviesIMDBResultset.ExactMatches.ToArray());
               lbExactMatches.DisplayMember = "Title";
               lbExactMatches.ValueMember = "Id";
               if (CurrentMovie.MovieChoosedFrom == choosedFrom.ExactMatches)
               {
                   int tempIndex = -1;
                   foreach (Movie item in lbExactMatches.Items)
                   {
                       if (item.Id == CurrentMovie.MovieIMDBInfo.Id)
                       {
                           tempIndex = lbExactMatches.Items.IndexOf(item);   
                       }
                   }
                   if (tempIndex != -1)
                       lbExactMatches.SetSelected(tempIndex, true);
               }
           }
           if (CurrentMovie.MoviesIMDBResultset.PartialMatches != null)
           {
               lbPartialMatches.Items.AddRange(CurrentMovie.MoviesIMDBResultset.PartialMatches.ToArray());
               lbPartialMatches.DisplayMember = "Title";
               lbPartialMatches.ValueMember = "Id";
               if (CurrentMovie.MovieChoosedFrom == choosedFrom.PartialMatches)
               {
                   int tempIndex = -1;
                   foreach (Movie item in lbPartialMatches.Items)
                   {
                       if (item.Id == CurrentMovie.MovieIMDBInfo.Id)
                       {
                           tempIndex = lbPartialMatches.Items.IndexOf(item);
                       }
                   }
                   if (tempIndex != -1)
                       lbPartialMatches.SetSelected(tempIndex, true);
               }
           }

           if (CurrentMovie.MovieStatus == moviesStatuses.ImdbSynched && CurrentMovie.MovieIMDBInfo != null)
           {
               BindImdbMovieDetailInfoControls(CurrentMovie.MovieIMDBInfo);
           }
       }

       private void BindImdbMovieDetailInfoControls(Movie theMovie)
       {
           
           lbl_title.Text = theMovie.Title;
           lbl_year.Text = theMovie.Year.ToString();
           if (theMovie.Genres != null)
               lbl_genres.Text = string.Join(",", theMovie.Genres.ToArray());
           if (theMovie.ProductionCompanies != null)
               lbl_studio.Text = theMovie.ProductionCompanies.FirstOrDefault();
           lbl_rating.Text = theMovie.UserRating.ToString();
           txt_plot.Text = theMovie.Description;

           try
           {
               pictureBox1.Image = theMovie.Poster;
           }
           catch
           {
               pictureBox1.Image = null;
           }
       }

       private void CleanImdbInfoControls()
       {
           lbPopularTitles.Items.Clear();
           lbPartialMatches.Items.Clear();
           lbExactMatches.Items.Clear();
           lbl_title.Text = string.Empty;
           lbl_year.Text = string.Empty;
           lbl_genres.Text = string.Empty;
           lbl_studio.Text = string.Empty;
           lbl_rating.Text = string.Empty;
           txt_plot.Text = string.Empty;
           pictureBox1.Image = null;
           btnApply.Enabled = false;
       }

       private void btnApply_Click(object sender, EventArgs e)
       {
           SetChoisedMovie();
           lbMoves_SelectedIndexChanged(lbMoves, new EventArgs());
       }

       private void SetChoisedMovie()
       {
           CurrentMovie.MovieIMDBInfo = SelectedMovie;

           if (lbPopularTitles.SelectedItem != null)
               CurrentMovie.MovieChoosedFrom = choosedFrom.PopularTitles;
           if (lbExactMatches.SelectedItem != null)
               CurrentMovie.MovieChoosedFrom = choosedFrom.ExactMatches;
           if (lbPartialMatches.SelectedItem != null)
               CurrentMovie.MovieChoosedFrom = choosedFrom.PartialMatches;

           CurrentMovie.MovieStatus = moviesStatuses.ImdbSynched;
           lbMoves.Refresh();

       }

       private void btnIMDBSynch_Click(object sender, EventArgs e)
       {
           Cursor.Current = Cursors.WaitCursor;
           lbMoves.Enabled = false;
           btnIMDBSingleSynch.Enabled = false;
           Imdb.FindMovie(lbMoves.SelectedValue.ToString());
           lbMoves.Enabled = true;
           btnIMDBSingleSynch.Enabled = true;
       }

       private void btnSynchroniseAll_Click(object sender, EventArgs e)
       {
           Cursor.Current = Cursors.WaitCursor;
           lbMoves.SetSelected(0, false);
           foreach (VMovie item in VMCollection)
           {
               if(item.MovieStatus == moviesStatuses.None)
                    Imdb.FindMovie(item.NewName);
           }
       }

       private void IMDBSynchDone(string movieSynchName)
       {
           lbMoves.Refresh();
       }

       private void lstBox_DrawItem(object sender, DrawItemEventArgs e)
       {
           if (e.Index != -1)
           {
               //
               // Draw the background of the ListBox control for each item.
               // Create a new Brush and initialize to a Black colored brush
               // by default.
               //
               e.DrawBackground();
               Brush myBrush = Brushes.Black;

               switch (((VMovie)((ListBox)sender).Items[e.Index]).MovieStatus)
               {
                   case moviesStatuses.None:
                       myBrush = Brushes.Black;
                       break;
                   case moviesStatuses.ImdbSynched:
                       myBrush = Brushes.Green;
                       break;
                   case moviesStatuses.ImdbNotSynched:
                       myBrush = Brushes.Red;
                       break;
                   default:
                       break;
               }
               // Draw the current item text based on the current 
               // Font and the custom brush settings.
               //
               e.Graphics.DrawString(((VMovie)(((ListBox)sender).Items[e.Index])).NewName,
                   e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
               //
               // If the ListBox has focus, draw a focus rectangle 
               // around the selected item.
               //
               e.DrawFocusRectangle();
           }
       }
       
       private void lstBoxMatches_DrawItem(object sender, DrawItemEventArgs e)
       {
           if (e.Index != -1)
           {
               //
               // Draw the background of the ListBox control for each item.
               // Create a new Brush and initialize to a Black colored brush
               // by default.
               //
               e.DrawBackground();
               Brush myBrush = Brushes.Black;
               if(CurrentMovie.MovieIMDBInfo != null && ((Movie)((ListBox)sender).Items[e.Index]).Id == CurrentMovie.MovieIMDBInfo.Id)
               {
                    myBrush = Brushes.Green;
               }

               // Draw the current item text based on the current 
               // Font and the custom brush settings.
               //
               e.Graphics.DrawString(((Movie)(((ListBox)sender).Items[e.Index])).Title,
                   e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
               //
               // If the ListBox has focus, draw a focus rectangle 
               // around the selected item.
               //
               e.DrawFocusRectangle();
           }
       }

       private void btnSerialize_Click(object sender, EventArgs e)
        {
            SaveMovieCollectionToConfig();
        }

       private void btnLoad_Click(object sender, EventArgs e)
        {
            LoadMovieCollectionFromConfig();
        }

       private void LoadMovieCollectionFromConfig()
        {
            VMovieCollection tempCollection = new VMovieCollection();
            XmlSerializer xser = new XmlSerializer(typeof(VMovieCollection));
            if (File.Exists(@"VMCollection.xml"))
            {
                var theStream = File.Open(@"VMCollection.xml", FileMode.Open, FileAccess.Read);
                tempCollection = (VMovieCollection)xser.Deserialize(theStream);
                theStream.Close();
            }

            //
            int i;
            VMovie tempVM;
            foreach (VMovie item in tempCollection)
            {
                if (VMCollection.Exists(p => p.ID == item.ID))
                {
                    item.RefreshMovePoster();
                    tempVM = VMCollection.Find(p => p.ID == item.ID);
                    i = VMCollection.IndexOf(tempVM);
                    VMCollection.Remove(tempVM);
                    VMCollection.Insert(i, item);
                }
            }
           
        }

       private void SaveMovieCollectionToConfig()
       {
           XmlSerializer xser = new XmlSerializer(typeof(VMovieCollection));
           MemoryStream m = new MemoryStream();
           xser.Serialize(m, VMCollection);
           File.WriteAllBytes(@"VMCollection.xml", m.GetBuffer());
           m.Close();
           MessageBox.Show("Saved !");
       }

       private void dgvMoviesNamesInfo_CellEndEdit(object sender, DataGridViewCellEventArgs e)
       {

       }
    }
}